package com.example.demo.controller;

import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.document.Document;
import org.springframework.ai.reader.tika.TikaDocumentReader;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.core.io.InputStreamResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

import java.time.LocalDate;
import java.util.List;

/**
 * @ClassName DashscopeController
 * @Description:
 * @Author: hgq
 * @CreateDate: 2025/2/10 14:51
 * @UpdateUser: hgq
 * @UpdateDate: 2025/2/10 14:51
 * @UpdateRemark:
 * @Version: 1.0
 */
@RestController
@RequestMapping("/dashscope")
@Slf4j
@AllArgsConstructor
public class DashscopeController {

    private ChatClient chatClient;
    private VectorStore vectorStore;

    @GetMapping(value = "/test/{msg}", produces = "text/html;charset=UTF-8")
    public String chat1(@PathVariable String msg) {
        log.info("你好啊啊啊啊啊啊");
        return "hello " + msg;
    }

    /**
     * 聊天
     *
     * @param message
     * @return
     */
    @GetMapping(value = "/chat", produces = "text/html;charset=UTF-8")
    public Flux<String> chat(@RequestParam(value = "message", defaultValue = "请问你是谁") String message) {
        Flux<String> stream = chatClient
                .prompt()
                .user(message)
                .system(promptSystemSpec -> promptSystemSpec.param("current_date", LocalDate.now().toString()))
                // .advisors(advisorSpec -> advisorSpec.param(QuestionAnswerAdvisor.FILTER_EXPRESSION, "type == 'Spring'"))
                // .advisors(advisorSpec -> advisorSpec.param(ChatMemory.CHAT_MEMORY_RETRIEVE_SIZE_KEY, 20))
                .stream()
                .content();
        return stream;
    }


    /**
     * 嵌入文件
     *
     * @param file 待嵌入的文件
     * @return 是否成功
     */
    @SneakyThrows
    @PostMapping("/embedding")
    public Boolean embedding(@RequestParam MultipartFile file) {
        // 从IO流中读取文件
        TikaDocumentReader tikaDocumentReader = new TikaDocumentReader(new InputStreamResource(file.getInputStream()));
        // 将文本内容划分成更小的块
        List<Document> splitDocuments = new TokenTextSplitter()
                .apply(tikaDocumentReader.read());
        // 存入向量数据库，这个过程会自动调用embeddingModel,将文本变成向量再存入。
        vectorStore.accept(splitDocuments);
        return true;
    }

}
